<template>
  <div>
    <el-tree
      :data="data"
      node-key="indexId"
      :draggable="type == 'add' || type == 'edit'"
      ref="selectTree"
      :expand-on-click-node="false"
      :highlight-current="true"
      :default-expand-all="true"
      :current-node-key="highlightedNodeId"
      @node-drop="handleDrop"
      @node-click="handleClick"
      :allow-drop="allowDrop"
    >
      <div class="custom_tree_node" slot-scope="{ data }">
        <div style="display: flex; align-items: center" class="rela">
          <div class="state" v-if="data.type == 1 || data.type == 2">
            <div v-if="data.status == 1" class="round"></div>
            <div v-if="data.status == 2" class="round_finish"></div>
            <div v-if="data.status == -1" class="round_fail"></div>
          </div>
          <div
            class="taskstateAbso taskstate flexEnd"
            v-if="data.type == 3 || data.type == 4"
          >
          <!-- 学生端课程目录 -->
            <div class="exam_icon" v-if=" data.examId && data.examSubmitType == 1 && !data.leaderPercentage">
              考
            </div>
            <div class="exam_icon" v-if="data.examId && (data.examSubmitType == 2 || (data.examSubmitType == 1 && data.leaderPercentage > 0))">
              组
            </div>
            <div class="leader_icon" v-if="data.homeworkId && data.homeworkSubmitType == 1 && !data.homeworkLeaderPercentage">
              作
            </div>
            <div class="leader_icon" v-if="data.homeworkId && (data.homeworkSubmitType == 2 || (data.homeworkSubmitType == 1 && data.homeworkLeaderPercentage > 0))">
              组
            </div>
          </div>
          <div
            class="taskstate flexEnd"
            v-if="data.type == 3 || data.type == 4"
          >
            <img
              v-if="data.studyStatus == 1"
              class="acting_icon"
              src="@/assets/images/courseAdd/acting_icon.png"
              alt="加载失败"
            />
            <i
              v-if="data.studyStatus == 2"
              class="el-icon-success acting_icon"
            ></i>
            <i
              v-if="data.studyStatus == -1"
              class="el-icon-error acting_icon"
            ></i>
          </div>
          <div
            v-if="!data.showRename"
            :style="{
              width: `calc(280px - 148px - ${(data.level - 1) * 16}px`,
            }"
            class="label"
          >
            {{ data.indexName }}
          </div>
          <div
            v-if="data.showRename"
            :style="{
              width: `calc(280px - 108px - ${(data.level - 1) * 16}px`,
            }"
            class="label"
          >
            <el-input
              clearable
              size="small"
              ref="resetName"
              @blur="editName(data)"
              @change="editName(data, 2)"
              v-model="data.indexName"
              placeholder="请输入名称"
              style="width: 100%"
            />
          </div>
        </div>
        <div class="flex_center">

          <div
            class="must_learn"
            v-if="
              data.mustLearnStatus == 1 && (data.type == 3 || data.type == 4)
            "
          >
            必学
          </div>
          <div
            class="choose_learn"
            v-if="
              data.mustLearnStatus == 2 && (data.type == 3 || data.type == 4)
            "
          >
            选学
          </div>
          <div v-if="type == 'add' || type == 'edit'" class="btn">
            <el-dropdown placement="bottom-start" trigger="click">
              <img
                class="more"
                src="@/assets/images/courseAdd/more.png"
                alt="加载失败"
                @click.stop=""
              />
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-if="data.type != 3 && data.type != 4"
                  @click.native.stop="handleEmit(data, 'addLink')"
                >
                  <span>添加子目录</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="data.type != 3 && data.type != 4"
                  @click.native.stop="handleEmit(data, 'addContent')"
                >
                  <span>添加内容层</span>
                </el-dropdown-item>
                <el-dropdown-item
                  @click.native.stop="handleEmit(data, 'rename')"
                >
                  <span>重命名</span>
                </el-dropdown-item>
                <el-dropdown-item
                  @click.native.stop="handleEmit(data, 'delete')"
                >
                  <span>删除</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </div>
    </el-tree>
  </div>
</template>

<script>
import { getItemById } from '../formatTreeData'

export default {
  name: 'courseTrees',
  data() {
    return {
      highlightedNodeId: '',
      highlightedNodeType: '',
      selectData: null
    }
  },
  props: {
    data: {
      type: Array,
      default: []
    },
    type: {
      type: String,
      default: ''
    },
    indexId: {
      type: [String, Number],
      default: ''
    }
  },
  watch: {
    data: {
      handler(val, oldVal) {
        // 继续学习  当前选中高亮和数据更新
        if (this.indexId) {
          this.highlightedNodeId = this.indexId
          this.$nextTick(() => {
            this.$refs.selectTree.setCurrentKey(this.indexId)
          })
          let item = getItemById(val, this.indexId)
          this.highlightedNodeType = item.type
          this.$emit('continueRefresh', item)
          return
        }
        if (oldVal.length == 0) {
          this.$nextTick(() => {
            this.highlightedNodeId = val[0].indexId
            this.highlightedNodeType = val[0].type
            this.$refs.selectTree.setCurrentKey(val[0].indexId)
            this.$emit('handleClick', val[0])
          })
        } else {
          if (oldVal[0].indexId != val[0].indexId) {
            this.highlightedNodeId = val[0].indexId
            this.highlightedNodeType = val[0].type
            this.$refs.selectTree.setCurrentKey(val[0].indexId)
            this.$emit('handleClick', val[0])
          }
          if (this.highlightedNodeId) {
            this.$nextTick(() => {
              this.$refs.selectTree.setCurrentKey(this.highlightedNodeId)
              this.$emit('refreshContent', this.highlightedNodeType)
            })
          }
        }
        val.forEach((item) => this.reverseCalculateStatus(item))
      },
      deep: true
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    // 1 学习中  2 已完成  0 未开始  -1 未通过
    /* 如果所有的 child 的 status 都等于 2，则将 obj 的 status 设置为2。
     * 有一个child 的 status 都等于 -1则将 obj 的 status 设置为-1。
     * 不满足以上条件，即否则，将 obj 的 status 设置为 1。*/
    calculateStatus(obj) {
      if (obj.children) {
        obj.status = obj.children.every((child) => {
          if (child.children) {
            this.calculateStatus(child)
          }
          return child.status == 2
        })
          ? 2
          : obj.children.some((child) => child.status == -1)
            ? -1
            : 1
      }
    },
    reverseCalculateStatus(obj) {
      if (obj.children) {
        obj.children.forEach((child) => this.reverseCalculateStatus(child))
        this.calculateStatus(obj)
      }
    },
    handleClick(data) {
      this.highlightedNodeId = data.indexId
      this.highlightedNodeType = data.type
      this.$emit('handleClick', data)
    },
    //设置子目录可以拖拽
    allowDrop(draggingNode, dropNode, type) {
      //注掉的是同级拖拽
      if (draggingNode.level === dropNode.level) {
        // 获取父节点信息
        const draggingParent = draggingNode.parent
        const dropParent = dropNode.parent
        if (draggingParent !== dropParent) {
          return false
        }
        return type === 'prev' || type === 'next'
      } else {
        // 不同级进行处理
        return false
      }
    },
    expandAll() {
      this.$nextTick(() => {
        this.expandAllNodes(this.$refs.selectTree.store.root)
      })
    },
    collapseAll() {
      this.$nextTick(() => {
        this.collapseAllNodes(this.$refs.selectTree.store.root)
      })
    },
    expandAllNodes(node) {
      if (node) {
        node.expanded = true
        if (node.childNodes) {
          node.childNodes.forEach((childNode) => {
            this.expandAllNodes(childNode)
          })
        }
      }
    },
    collapseAllNodes(node) {
      if (node) {
        node.expanded = false
        if (node.childNodes) {
          node.childNodes.forEach((childNode) => {
            this.collapseAllNodes(childNode)
          })
        }
      }
    },
    // 拖拽排序
    async handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log('tree drop: ', draggingNode, dropNode, dropType, ev)
      let parentChildren = this.findParentChildrenById(
        this.data,
        draggingNode.data.id,
        draggingNode.data.level
      )
      let ids = []
      if (parentChildren) {
        parentChildren.forEach((item) => {
          ids.push(item.id)
        })
        this.$emit('sort', ids.join(','))
      }
    },
    //返回节点所在层级的父节点的 children 数组
    findParentChildrenById(data, checkId, level, parentChildren = null) {
      if (level == 1) {
        let firstChildren = []
        for (let item of data) {
          firstChildren.push(item)
        }
        return firstChildren
      }
      for (let item of data) {
        if (item.id === checkId) {
          return parentChildren
        }
        if (item.children) {
          let result = this.findParentChildrenById(
            item.children,
            checkId,
            level,
            item.children
          )
          if (result) {
            return result
          }
        }
      }
      return null
    },
    handleEmit(data, name) {
      if (name == 'rename') {
        data.showRename = true
        this.$nextTick(() => {
          this.$refs['resetName'].focus()
        })
      } else {
        this.$emit(name, data)
      }
    },
    editName(data, type) {
      if (type == 2) {
        this.$emit('rename', data)
      } else {
        data.showRename = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
.custom_tree_node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 8px 0 0;
  box-sizing: border-box;

  .taskstateAbso {
    position: absolute;
    top: 0;
    left: -22px;
  }

  .taskstate {
    width: 40px;
    height: 21px;
    align-items: center;

    .exam_icon {
      width: 16px;
      height: 16px;
      background: #fa6400;
      border-radius: 3px;
      font-size: 12px;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 600;
      color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 4px;
    }

    .leader_icon {
      width: 16px;
      height: 16px;
      background: #4e8dff;
      border-radius: 3px;
      font-size: 12px;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 600;
      color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 4px;
    }

    .acting_icon {
      margin-right: 4px;
      width: 16px;
      height: 16px;
    }

    .el-icon-success {
      margin-right: 4px;
      font-size: 16px;
      color: #19b300;
    }

    .el-icon-error {
      margin-right: 4px;
      font-size: 16px;
      color: #ff3b30;
    }
  }

  .state {
    margin-right: 4px;
    position: relative;

    .round {
      width: 8px;
      height: 8px;
      border: 2px solid #19b300;
      border-radius: 50%;
    }

    .round_finish {
      width: 8px;
      height: 8px;
      background: #19b300;
      border-radius: 50%;
    }

    .round_fail {
      width: 8px;
      height: 8px;
      background: #ff3b30;
      border-radius: 50%;
    }
  }

  .flex_center {
    display: flex;
    align-items: center;

    .must_learn {
      color: rgb(40, 178, 139);
      background: rgb(196, 236, 226);
      width: 40px;
      height: 16px;
      border-radius: 8px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .choose_learn {
      color: rgb(44, 172, 255);
      background: rgb(213, 238, 255);
      width: 40px;
      height: 16px;
      border-radius: 8px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .btn {
      width: 20px;
      height: 20px;
      overflow: hidden;
      margin-left: 10px;
      display: flex;
      justify-content: center;
      align-items: center;

      .more {
        width: 18px;
        height: 12px;
      }
    }
  }

  .label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

::v-deep .el-tree-node__content {
  height: 40px;
}

::v-deep .el-icon-success,
::v-deep .el-icon-error {
  font-style: normal;
}
</style>
